package cn.kk.pzhu.gpaweb.config;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author KK
 * @CreateTime 2022/5/14
 */
@Configuration
//开启 PreAuthorize 注解
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    //该方法的主要用法
    //1.通过Java的方式 配置用户名/密码
    //2.在这里完成获得数据库中的用户信息
    //3.密码一定要加密（加密的方式一定要和注册是加密的方式一致）
    //4.登录认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //Spring Security 提供了BCryptPasswordEncoder类,实现Spring的PasswordEncoder接口使用BCrypt强哈希方法来加密密码。
        auth.inMemoryAuthentication().withUser("admin").password(passwordEncoder().encode("pzhu666")).roles("USER");;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http // 2. 登录配置表单认证方式
                .formLogin()
                .permitAll()
                .successForwardUrl("/admin")
                .failureUrl("/?error=true")
                .and()
                /*
                 * 默认允许所有路径所有人都可以访问，确保静态资源的正常访问。
                 * 后面再通过方法注解的方式来控制权限。
                 */
                .authorizeRequests().antMatchers("/**").permitAll()
                .and()
                .csrf()
                .disable();
    }
}
